package com.ylr.user.framework.service.impl;

import com.ylr.user.framework.entity.UserContactFlowEntity;
import com.ylr.user.framework.mapper.UserContactFlowMapper;
import com.ylr.user.framework.service.UserContactFlowService;
import com.ylr.user.framework.service.UserService;
import com.ylr.base.common.enums.CommonEnum;
import com.ylr.user.common.enums.UserContactFlowEnum;
import com.ylr.base.common.po.user.UserPo;
import com.ylr.base.common.utils.UserUtils;
import com.ylr.basic.framework.resolver.YbAesResolver;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Optional;

/**
 * Created by IntelliJ IDEA.
 *
 * @author wei
 * date: 2023-03-30 16:44:48
 * className: UserContactFlowServiceImpl 用户联系方式记录请求服务接口实现类
 * version: 1.0
 * description:
 */
@Service("userContactFlowService")
@AllArgsConstructor
public class UserContactFlowServiceImpl extends ServiceImpl<UserContactFlowMapper, UserContactFlowEntity> implements UserContactFlowService {

    private static final Logger log = LoggerFactory.getLogger(UserContactFlowServiceImpl.class);

    private final UserService userService;

    private final YbAesResolver ybAesResolver;

    @Override
    public void saveUserContactFlow(Long userId, Integer type, Integer mode, String contact, Boolean encode) {
        // 获取正在保存用户联系方式记录的用户
        UserPo userPo = UserUtils.getUser();

        if (encode) {
            // 数据加密
            contact = ybAesResolver.encryptToHex(contact);
        }

        Date date = new Date();

        UserContactFlowEntity userContactFlow = new UserContactFlowEntity();
        userContactFlow.setUserId(Optional.ofNullable(userId).orElse(userPo.getId()))
                .setType(type)
                .setMode(mode)
                .setContact(contact)
                .setDeleteStatus(CommonEnum.DELETE_NO.getValue())
                .setDeleteTime(date)
                .setDeleteUserId(CommonEnum.DEFAULT_ID.getLongValue())
                .setCreateTime(date)
                .setCreateUser(userPo.getUsername())
                .setCreateUserId(userPo.getId());
        // 插入数据
        baseMapper.insert(userContactFlow);
        log.info("用户联系方式记录添加完成");
    }

    @Override
    public void unbindPhone(String phone) {

        // 1、重置用户手机号
        userService.resetMobile();
        // 2、保存用户联系方式记录
        this.saveUserContactFlow(null, UserContactFlowEnum.MOBILE.getValue(), UserContactFlowEnum.UNBIND.getValue(), phone, Boolean.FALSE);
    }

    @Override
    public void unbindEmail(String email) {
        // 1、重置用户邮箱号
        userService.resetEmail();
        // 2、保存用户联系方式记录
        this.saveUserContactFlow(null, UserContactFlowEnum.EMAIL.getValue(), UserContactFlowEnum.UNBIND.getValue(), email, Boolean.FALSE);
    }



}